package com.simplemobiletools.camera.filter

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.atom.module.image.filter.*
import com.atom.module.logger.Logger
import com.simplemobiletools.camera.R
import com.simplemobiletools.camera.utils.Adapter
import com.simplemobiletools.camera.utils.FileUtil
import org.wysaid.common.SharedContext
import org.wysaid.nativePort.CGEImageHandler
import java.io.IOException
import java.lang.ref.ReferenceQueue
import java.lang.ref.SoftReference

/**
 * All rights Reserved, Designed By www.rongdasoft.com
 * @version V1.0
 * @Title: ModuleFIlterActivity
 * @Description:
 * @author: wuyongzheng
 * @date: 2022/3/18
 * @Copyright: 2022/3/18 www.rongdasoft.com Inc. All rights reserved.
 */
class ModuleFilterActivity : AppCompatActivity() {

    companion object {
        val queue = ReferenceQueue<ProcessImageTask>()
    }

    private var imgFilterSource: ImageView? = null
    private var imgFilterRenderer: ImageView? = null
    private var filterList: RecyclerView? = null
    private var currFilter: IImageFilter? = null
    private var resBitmap: Bitmap? = null

    private var mBackgroundThread: HandlerThread? = null
    private var mBackgroundHandler: Handler? = null

    fun onResumed() {
        object : HandlerThread("SimpleCameraBackground") {
            override fun run() {
                val glContext: SharedContext = SharedContext.create()
                glContext.makeCurrent()
                super.run()
                glContext.release()
            }
        }.also {
            it.start()
            mBackgroundHandler = Handler(it.looper)
            mBackgroundThread = it
        }
    }

    fun onPaused() {
        try {
            mBackgroundThread?.quitSafely()
            mBackgroundThread?.join()
            mBackgroundThread = null
            mBackgroundHandler = null
        } catch (e: InterruptedException) {
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_module_image_filter)

        imgFilterSource = findViewById(R.id.imgFilterSource)
        imgFilterRenderer = findViewById(R.id.imgFilterRenderer)

        val seekBar1: SeekBar = findViewById(R.id.seekBar1)
        val seekBar2: SeekBar = findViewById(R.id.seekBar2)
        val seekBar3: SeekBar = findViewById(R.id.seekBar3)

        with(findViewById<ImageView>(R.id.imgFilterSource)) {
            this.setOnClickListener {
                val builder = AlertDialog.Builder(it.context)
                val image = ImageView(it.context)
                image.setImageDrawable(this.drawable)
                builder.setView(image)
                val create = builder.create()
                create.show()
            }
        }

        with(findViewById<ImageView>(R.id.imgFilterRenderer)) {
            this.setOnClickListener {
                val builder = AlertDialog.Builder(it.context)
                val image = ImageView(it.context)
                image.setImageDrawable(this.drawable)
                builder.setView(image)
                builder.create().show()
            }
        }

        findViewById<View>(R.id.pickImage).setOnClickListener {
            pickImage()
        }

        findViewById<View>(R.id.photoImage).setOnClickListener {
            takePhoto()
        }

        findViewById<View>(R.id.resetDefault).setOnClickListener {
            resBitmap = BitmapFactory.decodeResource(
                this.resources,
                R.mipmap.module_filter
            ).also { bitmap ->
                setBitmap(bitmap)
            }
        }

        findViewById<View>(R.id.handleBitmap).setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                if (resBitmap == null) return
                if (resBitmap!!.isRecycled) return
                mBackgroundHandler?.post {
                    val renderer =
                        "@adjust sharpen 3.88 3.2 @curve RGB(0, 0)(100, 173)(255, 255) @adjust contrast 1.16 @beautify bilateral 100 20 1 @adjust contrast 1.04 @adjust exposure 0.06 @adjust blur 0.99 3.5 "
                    val handler = CGEImageHandler()
                    handler.initWithBitmap(resBitmap)
                    handler.setFilterWithConfig(renderer)
                    handler.processFilters()
                    //To accelerate this, you can add a Bitmap arg for "getResultBitmap",
                    // and reuse the Bitmap instead of recycle it every time.
                    val dst: Bitmap = handler.resultBitmap
                    v?.also {
                        findViewById<ImageView>(R.id.imgFilterRenderer).setImageBitmap(dst)
                        //ImageUtil.saveBitmap(dst)
                        //dst.recycle() //Maybe reuse it will be better.
                    }
                }
            }
        })

        seekBar1.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                reloadFilter(seekBar.progress, 1)
            }
        })
        seekBar2.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                reloadFilter(seekBar.progress, 2)
            }
        })
        seekBar3.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {
                reloadFilter(seekBar.progress, 3)
            }
        })

        val adapter =
            object : Adapter.Subject<FilterInfo>(object : Adapter.AbstractListener<FilterInfo>() {
                override fun onItemClick(
                    viewHolder: Adapter.ViewHolder<FilterInfo>?,
                    data: FilterInfo?
                ) {
                    data ?: return
                    currFilter = data.filter
                    when (data.filter) {
                        is SharpFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = false
                            seekBar3.isEnabled = false

                            seekBar1.progress = 50
                        }
                        is AutoAdjustFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = true
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter.contrastIntensity * 100).toInt()
                            seekBar2.progress = (data.filter.intensity * 100).toInt()
                        }
                        is EdgeFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = true
                            seekBar3.isEnabled = true

                            seekBar1.progress = (data.filter.rWeight * 100).toInt()
                            seekBar2.progress = (data.filter.gWeight * 100).toInt()
                            seekBar3.progress = (data.filter.bWeight * 100).toInt()
                        }
                        is BrickFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = false
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter.threshHold * 100 / 255f).toInt()
                        }
                        is PosterizeFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = false
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter._level * 5)
                        }
                        is PixelateFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = false
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter.pixelSize * 5)
                        }
                        is NeonFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = true
                            seekBar3.isEnabled = true

                            seekBar1.progress = (data.filter.rWeight * 100).toInt()
                            seekBar2.progress = (data.filter.gWeight * 100).toInt()
                            seekBar3.progress = (data.filter.bWeight * 100).toInt()
                        }
                        is BrightContrastFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = true
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter.brightnessFactor * 100).toInt()
                            seekBar2.progress = (data.filter.contrastFactor * 100).toInt()
                        }
                        is SaturationModifyFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = false
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter.saturationFactor * 100).toInt()
                        }
                        is ThresholdFilter -> {
                            seekBar1.isEnabled = true
                            seekBar2.isEnabled = false
                            seekBar3.isEnabled = false

                            seekBar1.progress = (data.filter.threshold * 100).toInt()
                        }
                    }

                    resBitmap?.also { bitmap ->
                        val processImageTask =
                            ProcessImageTask(this@ModuleFilterActivity, bitmap, data.filter)
                        SoftReference(processImageTask, queue).get()?.execute()
                    }
                }
            }) {
                override fun getItemViewType(position: Int, data: FilterInfo?): Int {
                    return R.layout.item_module_image_adapter
                }

                override fun onCreateViewHolder(
                    contentView: View,
                    viewType: Int
                ): Adapter.ViewHolder<FilterInfo> {
                    return ViewHolder(contentView)
                }
            }

        filterList = findViewById<RecyclerView?>(R.id.filterList)?.also {
            it.adapter = adapter
            it.layoutManager = LinearLayoutManager(it.context, RecyclerView.HORIZONTAL, false)
        }
        resBitmap = BitmapFactory.decodeResource(
            this.resources,
            R.mipmap.module_filter
        )
        imgFilterSource?.setImageBitmap(
            resBitmap
        )
        imgFilterRenderer?.setImageBitmap(
            resBitmap
        )
        loadData(adapter)

        onResumed()
    }

    override fun onDestroy() {
        onPaused()
        super.onDestroy()
    }

    private fun loadData(adapter: Adapter.Subject<FilterInfo>) {
        val filterArray = mutableListOf<FilterInfo>()
        filterArray.add(FilterInfo("NoFilter", EmptyFilter()))
        filterArray.add(FilterInfo("SharpFilter", SharpFilter()))


        filterArray.add(
            FilterInfo(
                "PosterizeFilter",
                PosterizeFilter(2)
            )
        )
        filterArray.add(
            FilterInfo(
                "ComicFilter",
                ComicFilter()
            )
        )

        filterArray.add(
            FilterInfo(
                "EdgeFilter",
                EdgeFilter()
            )
        )
        filterArray.add(
            FilterInfo(
                "PixelateFilter",
                PixelateFilter()
            )
        )
        filterArray.add(
            FilterInfo(
                "NeonFilter",
                NeonFilter()
            )
        )
        filterArray.add(
            FilterInfo(
                "BrightContrastFilter",
                BrightContrastFilter() // 变白增强
            )
        )
        filterArray.add(
            FilterInfo(
                "SaturationModifyFilter",
                SaturationModifyFilter()
            )
        )
        filterArray.add(
            FilterInfo(
                "ThresholdFilter",
                ThresholdFilter()
            )
        )
        filterArray.add(
            FilterInfo(
                "BlockPrintFilter",
                BlockPrintFilter()
            )
        )
        filterArray.add(
            FilterInfo(
                "BrickFilter",
                BrickFilter()
            )
        )

        filterArray.add(
            FilterInfo(
                "AutoAdjustFilter",
                AutoAdjustFilter()
            )
        )
        //  filterArray.add(FilterInfo("SoftGlowFilter", SoftGlowFilter(10, 0.1f, 0.1f)))
        //filterArray.add(FilterInfo("HslModifyFilter", HslModifyFilter(20f))) // 20 -- 300
        // filterArray.add(FilterInfo("VideoFilter_VIDEO_STAGGERED",VideoFilter(VideoFilter.VIDEO_TYPE.VIDEO_STAGGERED)))
        // filterArray.add(FilterInfo("VideoFilter_VIDEO_TRIPED", VideoFilter(VideoFilter.VIDEO_TYPE.VIDEO_TRIPED)))
        // filterArray.add(FilterInfo("VideoFilter_VIDEO_3X3", VideoFilter(VideoFilter.VIDEO_TYPE.VIDEO_3X3)))
        // filterArray.add(FilterInfo("VideoFilter_VIDEO_DOTS", VideoFilter(VideoFilter.VIDEO_TYPE.VIDEO_DOTS)))
        //filterArray.add(FilterInfo("TileReflectionFilter_1", TileReflectionFilter(20, 8, 45, 1.toByte())))
        // filterArray.add(FilterInfo("TileReflectionFilter_2", TileReflectionFilter(20, 8, 45, 2.toByte())))
        // filterArray.add(FilterInfo("FillPatternFilter", FillPatternFilter(this@ModuleFilterActivity, R.drawable.ic_settings_cog)))
        // filterArray.add(FilterInfo("FillPatternFilter", FillPatternFilter(this@ModuleFilterActivity, R.drawable.ic_settings_cog)))
        // filterArray.add(FilterInfo("MirrorFilter", MirrorFilter(true)))
        // filterArray.add(FilterInfo("MirrorFilter", MirrorFilter(false)))
        //  filterArray.add(FilterInfo("YCBCrLinearFilter", YCBCrLinearFilter(YCBCrLinearFilter.Range(-0.3f, 0.3f))))
        // filterArray.add(FilterInfo("YCBCrLinearFilter", YCBCrLinearFilter(YCBCrLinearFilter.Range(-0.276f, 0.163f), YCBCrLinearFilter.Range(-0.202f, 0.5f))))

        // filterArray.add(FilterInfo("TexturerFilter_CloudsTexture", TexturerFilter(CloudsTexture(), 0.8, 0.8)))
        // filterArray.add(FilterInfo("TexturerFilter_LabyrinthTexture", TexturerFilter(LabyrinthTexture(), 0.8, 0.8)))
        // filterArray.add(FilterInfo("TexturerFilter_MarbleTexture", TexturerFilter(MarbleTexture(), 1.8, 0.8)))
        // filterArray.add(FilterInfo("TexturerFilter_WoodTexture", TexturerFilter(WoodTexture(), 0.8, 0.8)))
        //filterArray.add(FilterInfo("TexturerFilter_TextileTexture", TexturerFilter(TextileTexture(), 0.8, 0.8)))

        // filterArray.add(FilterInfo("ZoomBlurFilter", ZoomBlurFilter(30)))
        // filterArray.add(FilterInfo("ThreeDGridFilter", ThreeDGridFilter(16, 100)))
        // filterArray.add(FilterInfo("ColorToneFilter", ColorToneFilter(Color.rgb(33, 168, 254), 192)))
        // filterArray.add(FilterInfo("ColorToneFilter_0x00FF00", ColorToneFilter(0x00FF00, 192)))
        //  filterArray.add(FilterInfo("ColorToneFilter_0xFF0000", ColorToneFilter(0xFF0000, 192)))
        //  filterArray.add(FilterInfo("ColorToneFilter_0x00FFFF", ColorToneFilter(0x00FFFF, 192)))

        //filterArray.add(FilterInfo("TileReflectionFilter", TileReflectionFilter(20, 8)))
        // filterArray.add(FilterInfo("BlindFilter_0xffffff", BlindFilter(true, 96, 100, 0xffffff)))
        //filterArray.add(FilterInfo("BlindFilter_0x000000", BlindFilter(false, 96, 100, 0x000000)))
        // filterArray.add(FilterInfo("RaiseFrameFilter", RaiseFrameFilter(20)))
        // filterArray.add(FilterInfo("ShiftFilter", ShiftFilter(10)))
        // filterArray.add(FilterInfo("WaveFilter", WaveFilter(25, 10)))
        //  filterArray.add(FilterInfo("BulgeFilter", BulgeFilter(-97)))

        //  filterArray.add(FilterInfo("TwistFilter", TwistFilter(27, 106)))
        // filterArray.add(FilterInfo("RippleFilter", RippleFilter(38, 15, true)))

        // filterArray.add(FilterInfo("IllusionFilter_3", IllusionFilter(3)))
        //filterArray.add(FilterInfo("SupernovaFilter_0x00FFFF", SupernovaFilter(0x00FFFF, 20, 100)))

        //filterArray.add(FilterInfo("LensFlareFilter", LensFlareFilter()))

        //filterArray.add(FilterInfo("GammaFilter_50", GammaFilter(50)))

        // filterArray.add(FilterInfo("SceneFilter_Scene_5", SceneFilter(5f, Gradient.Scene())))
        // filterArray.add(FilterInfo("SceneFilter_Scene1_5", SceneFilter(5f, Gradient.Scene1())))
        //filterArray.add(FilterInfo("SceneFilter_Scene2_5", SceneFilter(5f, Gradient.Scene2())))
        // filterArray.add(FilterInfo("SceneFilter_Scene2_5", SceneFilter(5f, Gradient.Scene3())))
        // filterArray.add(FilterInfo("SceneFilter_Scene3_10", SceneFilter(10f, Gradient.Scene3())))
        // filterArray.add(FilterInfo("FilmFilter_80", FilmFilter(80f)))
        // filterArray.add(FilterInfo("FocusFilter", FocusFilter()))
        // filterArray.add(FilterInfo("CleanGlassFilter", CleanGlassFilter()))
        // filterArray.add(FilterInfo("PaintBorderFilter_0x00FF00", PaintBorderFilter(0x00FF00)))
        // filterArray.add(FilterInfo("PaintBorderFilter_0x00FFFF", PaintBorderFilter(0x00FFFF)))
        // filterArray.add(FilterInfo("PaintBorderFilter_0xFF0000", PaintBorderFilter(0xFF0000)))
        // filterArray.add(FilterInfo("LomoFilter", LomoFilter()))
        //  filterArray.add(FilterInfo("InvertFilter", InvertFilter()))
        // filterArray.add(FilterInfo("BlackWhiteFilter", BlackWhiteFilter()))

        //filterArray.add(FilterInfo("BigBrotherFilter", BigBrotherFilter()))
        //  filterArray.add(FilterInfo("MonitorFilter", MonitorFilter()))
        //  filterArray.add(FilterInfo("ReliefFilter", ReliefFilter()))

        //  filterArray.add(FilterInfo("NoiseFilter", NoiseFilter()))
        // filterArray.add(FilterInfo("BannerFilter_10_true", BannerFilter(10, true)))
        // filterArray.add(FilterInfo("BannerFilter_10_false", BannerFilter(10, false)))
        // filterArray.add(FilterInfo("RectMatrixFilter", RectMatrixFilter()))

        //  filterArray.add(FilterInfo("GaussianBlurFilter", GaussianBlurFilter()))
        // filterArray.add(FilterInfo("LightFilter", LightFilter()))
        // filterArray.add(FilterInfo("MistFilter", MistFilter()))
        // filterArray.add(FilterInfo("MosaicFilter", MosaicFilter()))
        // filterArray.add(FilterInfo("OilPaintFilter", OilPaintFilter()))

        // filterArray.add(FilterInfo("RadialDistortionFilter", RadialDistortionFilter()))

        //filterArray.add(FilterInfo("ReflectionFilter_true", ReflectionFilter(true)))

        // filterArray.add(FilterInfo("ReflectionFilter_false", ReflectionFilter(false)))

        //filterArray.add(FilterInfo("SaturationModifyFilter", SaturationModifyFilter()))
        // filterArray.add(FilterInfo("SmashColorFilter", SmashColorFilter()))
        // filterArray.add(FilterInfo("TintFilter", TintFilter()))
        // filterArray.add(FilterInfo("VignetteFilter", VignetteFilter()))

        // filterArray.add(FilterInfo("ColorQuantizeFilter", ColorQuantizeFilter()))
        // filterArray.add(FilterInfo("WaterWaveFilter", WaterWaveFilter()))
        // filterArray.add(FilterInfo("VintageFilter", VintageFilter()))
        // filterArray.add(FilterInfo("OldPhotoFilter", OldPhotoFilter()))
        //filterArray.add(FilterInfo("SepiaFilter", SepiaFilter()))
        // filterArray.add(FilterInfo("RainBowFilter", RainBowFilter()))
        //filterArray.add(FilterInfo("FeatherFilter", FeatherFilter()))
        // filterArray.add(FilterInfo("XRadiationFilter", XRadiationFilter()))
        // filterArray.add(FilterInfo("NightVisionFilter", NightVisionFilter()))
        adapter.addAll(filterArray)
    }

    private fun reloadFilter(progress: Int, tag: Int) {
        currFilter?.also {
            when (it) {
                is SharpFilter -> {
                    when (tag) {
                        1 -> {
                            it.set_step((progress - 50) / 10)
                        }
                        2 -> {

                        }
                        3 -> {

                        }
                    }
                }
                is AutoAdjustFilter -> {
                    when (tag) {
                        1 -> {
                            it.contrastIntensity = progress / 100f
                        }
                        2 -> {
                            it.intensity = progress / 100f
                        }
                        3 -> {

                        }
                    }
                }
                is BrickFilter -> {
                    it.threshHold = ((progress / 100f * 255).toInt())
                }
                is PosterizeFilter -> {
                    it._level = (progress / 5)
                }
                is ComicFilter -> {

                }
                is EdgeFilter -> {
                    when (tag) {
                        1 -> {
                            it.rWeight = progress / 100.0
                        }
                        2 -> {
                            it.gWeight = progress / 100.0
                        }
                        3 -> {
                            it.bWeight = progress / 100.0
                        }
                    }
                }
                is PixelateFilter -> {
                    it.pixelSize = progress / 5
                }
                is NeonFilter -> {
                    when (tag) {
                        1 -> {
                            it.rWeight = progress / 100.0
                        }
                        2 -> {
                            it.gWeight = progress / 100.0
                        }
                        3 -> {
                            it.bWeight = progress / 100.0
                        }
                    }
                }
                is BrightContrastFilter -> {
                    when (tag) {
                        1 -> {
                            it.brightnessFactor = progress / 100f
                        }
                        2 -> {
                            it.contrastFactor = progress / 100f
                        }
                        3 -> {

                        }
                    }
                }
                is SaturationModifyFilter -> {
                    when (tag) {
                        1 -> {
                            it.saturationFactor = progress / 100f
                        }
                        2 -> {

                        }
                        3 -> {
                        }
                    }
                }
                is ThresholdFilter -> {
                    when (tag) {
                        1 -> {
                            it.threshold = progress / 100f
                        }
                        2 -> {

                        }
                        3 -> {
                        }
                    }
                }
                is BlockPrintFilter -> {

                }
            }
            resBitmap?.also { bitmap ->
                val processImageTask = ProcessImageTask(this@ModuleFilterActivity, bitmap, it)
                SoftReference(processImageTask, queue).get()?.execute()
            }
        } ?: let {
            Toast.makeText(it, "请选择滤镜", Toast.LENGTH_SHORT).show()
        }
    }

    class ViewHolder(view: View) : Adapter.ViewHolder<FilterInfo>(view) {
        val name: TextView = view.findViewById(R.id.imageFilterName)
        override fun onBind(data: FilterInfo?) {
            data ?: return
            name.text = data.name
        }
    }

    @SuppressLint("StaticFieldLeak")
    class ProcessImageTask(
        private val activity: Activity,
        private val bitmap: Bitmap,
        private val filter: IImageFilter?
    ) :
        AsyncTask<Void?, Void?, Bitmap?>() {
        var start: Long = System.currentTimeMillis()

        @SuppressLint("StaticFieldLeak")
        private val textView: TextView = activity.findViewById(R.id.runtime)

        @SuppressLint("StaticFieldLeak")
        private val imgFilterRenderer: ImageView = activity.findViewById(R.id.imgFilterRenderer)

        override fun onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute()
            start = System.currentTimeMillis()
            textView.text = "渲染中....."
        }

        @SuppressLint("SetTextI18n")
        override fun onPostExecute(result: Bitmap?) {
            super.onPostExecute(result)
            if (result != null) {
                super.onPostExecute(result)
                imgFilterRenderer.setImageBitmap(result)
                val space = System.currentTimeMillis() - start
                textView.text =
                    "渲染完成 $space ms [${result.width}-${result.height}] ${result.byteCount / 1024 / 1024}MB \n ${filter?.toString()}"
            }
        }

        fun printf(tag: String) {
            var poll = queue.poll()
            while (poll != null) {
                Log.e("ModuleFilterActivity", "$tag  ${poll.get()}")
                poll = queue.poll()
            }
        }

        override fun doInBackground(vararg params: Void?): Bitmap? {
            printf("start")
            var img: Image? = null
            try {
                img = Image(bitmap)
                if (filter != null) {
                    img = filter.process(img)
                    img.copyPixelsFromBuffer()
                }
                return img!!.getImage()
            } catch (e: Exception) {
                if (img != null && img.destImage.isRecycled) {
                    img.destImage.recycle()
                    img.destImage = null
                    System.gc()
                }
            } finally {
                if (img != null && img.image.isRecycled) {
                    img.image.recycle()
                    img.image = null
                    System.gc()
                }
            }
            printf("end")
            return null
        }
    }

    private var imageUri: Uri? = null
    private fun takePhoto() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (takePictureIntent.resolveActivity(this.packageManager) != null) {
            val values = ContentValues()
            values.put(MediaStore.Images.Media.TITLE, "New Picture")
            values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera")
            this.imageUri =
                this.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, this.imageUri)
            this.startActivityForResult(
                takePictureIntent,
                1024
            )
        }
    }

    private fun pickImage() {
        val intent = Intent(Intent.ACTION_PICK, null)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(
            intent,
            2048
        )
    }

    private fun handleFile(bitmap: Bitmap, degree: Int) {
        val spBitmap = rotaingImageView(degree, bitmap)
        val matrix = Matrix()
        matrix.setScale(0.5f, 0.5f)
        setBitmap(
            Bitmap.createBitmap(
                spBitmap!!, 0, 0, spBitmap.width,
                spBitmap.height, matrix, true
            )
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1024 && resultCode == RESULT_OK) {
            try {
                if (imageUri != null) {
                    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
                    val realPathFromURI: String? = FileUtil.getFilePathByUri(this, imageUri)
                    handleFile(bitmap, readPictureDegree(realPathFromURI))
                }
            } catch (e: IOException) {
                Logger.e(e)
            }
        }
        if (requestCode == 2048 && resultCode == RESULT_OK) {
            data ?: return
            imageUri = data.data
            try {
                if (imageUri != null) {
                    val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
                    val realPathFromURI: String? = FileUtil.getFilePathByUri(this, imageUri)
                    handleFile(bitmap, readPictureDegree(realPathFromURI))
                }
            } catch (e: IOException) {
                Logger.e(e)
            }
        }
    }

    fun setBitmap(bitmap: Bitmap) {
        resBitmap = bitmap
        imgFilterSource?.setImageBitmap(
            bitmap
        )
        currFilter?.also {
            val processImageTask = ProcessImageTask(this@ModuleFilterActivity, bitmap, it)
            SoftReference(processImageTask, queue).get()?.execute()
        } ?: let {
            imgFilterRenderer?.setImageBitmap(
                bitmap
            )
        }
    }

    fun rotaingImageView(angle: Int, bitmap: Bitmap): Bitmap? {
        val matrix = Matrix()
        matrix.postRotate(angle.toFloat())
        return Bitmap.createBitmap(
            bitmap, 0, 0,
            bitmap.width, bitmap.height, matrix, true
        )
    }

    fun readPictureDegree(path: String?): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(path!!)
            val orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: IOException) {
            Log.e(
                "DocumentActivity",
                e.message!!
            )
        }
        return degree
    }
}
